/*
 * @Description: 电影服务层
 * @Author: fhw
 * @Date: 2024-06-15
 */

import { Injectable, UseFilters } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Connection, In, QueryRunner, Repository } from 'typeorm';
import { CreateMovieDto, UpdateMovieDto, GetMovieDto } from './dto/movie.dto';
import { HttpExceptionFilter } from 'src/common/http-exception.filter';
import { getPagination, throwHttp } from 'src/utlis';
import { isTrue } from 'src/utlis/tools';
import { IdDto } from 'src/common/dto/dto';
import { MovieEntity } from 'src/modules/admin/movies/entities/movie.entity';
import { MoviesEpisodeEntity } from 'src/modules/admin/movies-episode/entities/movies-episode.entity';

@Injectable()
export class MovieService {
  constructor(
    @InjectRepository(MovieEntity)
    private readonly movieRepository: Repository<MovieEntity>,
    @InjectRepository(MoviesEpisodeEntity)
    private readonly moviesEpisodeRepository: Repository<MoviesEpisodeEntity>,
  ) { }

  /** 获取电影 */
  @UseFilters(new HttpExceptionFilter())
  async getMoviePage(params: GetMovieDto, lang: string) {
    try {
      const { name, free, status, categoryId, isRecommend } = params;
      const where: GetMovieDto = {
        name,
        status,
        lang,
        free,
        isRecommend,

      };
      // 过滤掉为 `undefined` 的属性
      Object.keys(where).forEach(key => where[key] === undefined && delete where[key]);
      // 分页
      const { pageSize, pageNum } = getPagination({
        pageSize: params.pageSize,
        pageNum: params.pageNum,
      });

      const [data, total] = await this.movieRepository.findAndCount({
        where: {
          ...where,
          category: {
            id: categoryId
          }
        },
        cache: false,
        skip: pageNum * pageSize,  // 跳过的数量
        take: pageSize,  // 每页的数量
        order: { createDate: 'DESC' },  // 排序
        relations: ['tags', 'category', 'episodes'],
      });
      return {
        data: data.map(item => {
          return {
            ...item,
            tags: item?.tags?.map(tag => tag.name),
            category: item?.category?.map(cat => cat.name),
            episodeCount: item?.episodes?.length || 0, // 计算每个电影的剧集数量
          }
        }),
        total,
        pageSize,
        pageNum: pageNum + 1,
      };
    } catch (error) {
      throwHttp(error.message);
    }
  }

  /** 获取电影详情 */
  @UseFilters(new HttpExceptionFilter())
  async getMovieInfo(id: number, lang: string) {
    try {
      const data = await this.movieRepository.findOne({
        where: { id, lang },
        cache: true,
        relations: [
          'category'
        ],
      });
      const episodeCount = await this.moviesEpisodeRepository.count({
        where: { movies: { id } },
        cache: true,
      });
      return {
        ...data,
        episodeCount
      }
    } catch (error) {
      throwHttp(error.message);
    }
  }
  /** 获取推荐剧集 */
  @UseFilters(new HttpExceptionFilter())
  async getRecommendations(movieId: number, lang: string) {
    const movie = await this.movieRepository.findOne({
      where: { id: movieId, lang },
      relations: ['recommendedMovies', 'recommendedMovies.tags', 'recommendedMovies.category', 'recommendedMovies.episodes',],
      order: { createDate: 'DESC' },
    });
    if (!movie) {
      throwHttp('电影不存在');
    }
    return movie.recommendedMovies.map(item => {
      const episodeCount = item?.episodes?.length || 0 // 计算每个电影的剧集数量
      delete item?.episodes
      return {
        ...item,
        tags: item.tags.map(tag => tag.name),
        category: item.category.map(cat => cat.name),
        episodeCount
      }
    });
  }

  /** 获取首页电影数据 */
  @UseFilters(new HttpExceptionFilter())
  async getHomeMovie(lang: string) {
    try {
      const options: any = {
        cache: false,
        order: { createDate: 'DESC' },  // 排序
        relations: ['tags', 'category', 'episodes'],
      }
      const mustWatch = await this.movieRepository.find({
        where: {
          isMustWatch: true,
          lang
        },
        ...options,
      });
      const featured = await this.movieRepository.find({
        where: {
          isFeatured: true,
          lang
        },
        ...options,
      });
      const currentlyAiring = await this.movieRepository.find({
        where: {
          isCurrentlyAiring: true,
          lang
        },
        cache: false,
        ...options,
      });
      return {
        // 必看剧
        mustWatch: mustWatch.map(item => ({
          ...item,
          tags: item.tags.map(tag => tag.name),
          category: item.category.map(cat => cat.name),
          episodeCount: item?.episodes?.length || 0, // 计算每个电影的剧集数量
        })),
        // 精彩剧集
        featured: featured.map(item => ({
          ...item,
          tags: item.tags.map(tag => tag.name),
          category: item.category.map(cat => cat.name),
          episodeCount: item?.episodes?.length || 0, // 计算每个电影的剧集数量
        })),
        // 正在热映
        currentlyAiring: currentlyAiring.map(item => ({
          ...item,
          tags: item.tags.map(tag => tag.name),
          category: item.category.map(cat => cat.name),
          episodeCount: item?.episodes?.length || 0, // 计算每个电影的剧集数量
        })),
      };
    } catch (error) {
      throwHttp(error.message);
    }
  }
}
